package personal.wang.cli;

import io.netty.util.internal.StringUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import personal.wang.domain.TestpointInfoProto;
import personal.wang.config.DataMockYamlReader;
import personal.wang.constant.AppConstant;
import personal.wang.utils.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.nio.file.FileVisitOption.*;

/**
 * @className: CliParameterParser
 * @Description:
 * @Author: wangyifei
 * @Date: 2025/2/17 15:27
 */
public class CliParameterParser {
    private static Logger logger = LoggerFactory.getLogger(CliParameterParser.class);
    private static final String BACKUP_PATH_TAG_NAME = "backup_path" ;
    private static final String SEND_MESSAGE_NUMBER_TAG_NAME = "msg_num" ;
    private static final String SEND_RECORD_BATCH_TAG_NAME = "batch_size";
    private static final String PRODUCER_TYPE_TAG_NAME = "kafka.producer_type" ;
    private static final String PRODUCER_NUMBER_TAG_NAME = "producer_num" ;
    private static final String KAFKA_BOOTSTRAP_TAG_NAME = "kafka.bootstrap" ;
    private static final String KAFKA_TOPIC_TAG_NAME = "kafka.topic_name" ;
    private static final String PACKAGE_TAG_NAME = "template_path";
    private static final String TEMPLATE_PACKAGE_TAG_NAME = "tpl";
    private static final String DICTIONARY_PACKAGE_TAG_NAME = "dictionary";
    private static final String TEST_POINT_TAG_NAME = "test_points";
    private static final String ACTIVE_TAG_NAME = "true" ;
    private static final String TABLE_NAME_TAG_NAME = "table_name" ;
    private static final String IS_ACTIVE_TAG_NAME = "is_active" ;
    public static List<TestpointInfoProto.TestPointInfo> parser(String path){
        File file = new File(path);
        String basePath = file.getParentFile().getAbsolutePath();
        List<TestpointInfoProto.TestPointInfo> list = new ArrayList<>();
        Map testPoints = DataMockYamlReader.getValueAsMap(path , TEST_POINT_TAG_NAME);
        Set set = testPoints.entrySet();
        Map.Entry entry = null ;
        for (Object o : set) {
            if(o instanceof Map.Entry) {
                entry = (Map.Entry)o ;
                TestpointInfoProto.TestPointInfo.Builder testPointBuilder = TestpointInfoProto.TestPointInfo.newBuilder();
                Object value = entry.getValue();
                String name = entry.getKey().toString();
                if(value instanceof Map) {
                    Map map = (Map<?, ?>) value;
                    if (!ACTIVE_TAG_NAME.equals(map.get(IS_ACTIVE_TAG_NAME).toString())) {
                        continue;
                    }
                    File tplFile = new File(basePath + File.separator
                            + "tpl"
                            + File.separator
                            + map.get(PACKAGE_TAG_NAME).toString());
                    testPointBuilder.setTableName(map.get(TABLE_NAME_TAG_NAME).toString());
                    testPointBuilder.setPath(tplFile.getAbsolutePath());
                    String tplCnt = null ;
                    try {
                        tplCnt = FileUtils.readFileToString( tplFile
                                , StandardCharsets.UTF_8);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    testPointBuilder.setTplCnt(tplCnt);
                    testPointBuilder.setMsgNumber(Integer.parseInt(map.get("msg_num").toString()));
                    testPointBuilder.setDicPath(basePath + File.separator + DICTIONARY_PACKAGE_TAG_NAME);
                    testPointBuilder.setTplPath(basePath + File.separator + TEMPLATE_PACKAGE_TAG_NAME);
                    File dict = new File(basePath + File.separator + DICTIONARY_PACKAGE_TAG_NAME);
                    Path p = Paths.get(dict.getAbsolutePath());
                    try(Stream<Path> walk = Files.walk(p)){
                        List<Path> dic = walk.filter(Files::isRegularFile)
                                .filter(pth -> pth.toString().endsWith(".dic") && !pth.toString().endsWith("sub.dic"))
                                .collect(Collectors.toList());
                        for (Path path1 : dic) {
                            for (String readLine : FileUtils.readLines(path1.toFile(), StandardCharsets.UTF_8)) {
                                String[] split = readLine.split("=");
                                String key = split[0];
                                for (String s : split[1].split("\\|\\|\\|")) {
                                    if(s.startsWith("$File{")){
                                        s =
                                                FileUtils.readFileToString(
                                                        new File(path1.toFile().getParent()
                                                                + File.separator
                                                                + s.replace("$File{",StringUtil.EMPTY_STRING)
                                                                   .replace("}", StringUtil.EMPTY_STRING))
                                                        , StandardCharsets.UTF_8);
                                    }
                                    testPointBuilder.putDicCnt(key , s);
                                }
                            }
                        }
                    }catch (IOException e){
                        logger.error("{}" , e.getMessage());
                    }

                    testPointBuilder.setBatchSize((Integer)map.get(SEND_RECORD_BATCH_TAG_NAME));
                    String bootstrap = DataMockYamlReader.getValueAsString(path , TEST_POINT_TAG_NAME
                            + AppConstant.DOT + entry.getKey() + AppConstant.DOT + KAFKA_BOOTSTRAP_TAG_NAME);
                    String topics = DataMockYamlReader.getValueAsString(path , TEST_POINT_TAG_NAME
                            + AppConstant.DOT + entry.getKey() + AppConstant.DOT + KAFKA_TOPIC_TAG_NAME);
                    String producerType = DataMockYamlReader.getValueAsString(path , TEST_POINT_TAG_NAME
                            + AppConstant.DOT + entry.getKey() + AppConstant.DOT + PRODUCER_TYPE_TAG_NAME);
                    testPointBuilder.setKafkaBootstrap(bootstrap);
                    testPointBuilder.setProducerType(producerType);
                    for (String topic : topics.split(AppConstant.COMMA)) {
                        testPointBuilder.addTopicNames(topic);
                    }
                    testPointBuilder.setMsgNumber((Integer)map.get(SEND_MESSAGE_NUMBER_TAG_NAME));
                    testPointBuilder.setName(name);
                    testPointBuilder.setProducerNumber((Integer)map.get(PRODUCER_NUMBER_TAG_NAME));
                    testPointBuilder.setBackupPath(StringUtil.EMPTY_STRING);
                    testPointBuilder.setSummaryPath(basePath);
                    list.add(testPointBuilder.build());
                }
            }
        }
        return list;
    }
}
